package com.kirk.cts.core.loader;

import com.kirk.cts.core.constants.Config;
import com.kirk.cts.core.utils.PropertiesHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.Enumeration;
import java.util.Properties;

/**
 * <p> ConfigLoader.java </p>
 *
 * @version 1.0.0
 * @Author kirkliu
 * @Date 2020-08-29 22:22
 * @Description 加载配置参数
 */
public class ConfigLoader {
    protected static Logger log = Logger.getLogger(ConfigLoader.class);

    /**
     * 爬虫配置参数文件路径
     */
    private static String CRAWLER_APP_PROPERTIES_PATH = "/CrawlerToolApp.properties";

    private static String classLoaderPath = ConfigLoader.class.getClassLoader().getResource("").getPath();

    public static void loadConfig() {

        log.info("开始加载爬虫参数配置文件:" + CRAWLER_APP_PROPERTIES_PATH);

        PropertiesHelper propertiesHelper = new PropertiesHelper();
        Properties properties = propertiesHelper.loadProperties(CRAWLER_APP_PROPERTIES_PATH);
        Enumeration<?> propNames = properties.propertyNames();
        String propKey = null;
        String propValue = null;
        while (propNames.hasMoreElements()) {
            propKey = (String) propNames.nextElement();
            propValue = properties.getProperty(propKey);
            log.info("加载配置：" + propKey + ",路径为：" + propValue);
            if (!isBlank(propKey) && !isBlank(propValue)) {
                Config.CRAWLER_CONFIG_RESOURCES_PATH_MAP.put(propKey, propValue);
                Config.CRAWLER_CONFIG_MAP.put(propKey, propertiesHelper.propertiesToMap(propValue));
            }
        }
        Config.CRAWLER_CONFIG_MAP.get(Config.CRAWLER_CONFIG_KEY_CORE).put(Config.CRAWLER_CONFIG_KEY_CORE_CLASS_LOADER_PATH, classLoaderPath);

        log.info("爬虫参数配置文件加载完成");
    }

    /**
     * 判断配置参数值是否为空
     *
     * @param value 配置参数值
     * @return
     */
    private static boolean isBlank(String value) {
        return StringUtils.isBlank(StringUtils.trim(value));
    }
}
